<template>
  <div class="user-management">
    <!-- 搜索条件 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
        <el-form-item label="用户名称" prop="userName">
          <el-input
            v-model="queryParams.userName"
            placeholder="请输入用户名称"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input
            v-model="queryParams.phonenumber"
            placeholder="请输入手机号码"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作工具栏 -->
    <el-card class="table-card" shadow="never">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >新增用户</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
          >导出</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="el-icon-refresh"
            size="mini"
            @click="refreshData"
          >刷新</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <!-- 用户列表表格 -->
      <el-table
        v-loading="loading"
        :data="userList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="用户ID" prop="userId" width="80" />
        <el-table-column label="用户名称" prop="userName" width="120" show-overflow-tooltip />
        <el-table-column label="手机号码" prop="phonenumber" width="130" />
        <el-table-column label="信用分" prop="creditScore" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="getCreditScoreType(scope.row.creditScore)" size="medium">
              {{ scope.row.creditScore || '--' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="信用等级" width="120" align="center">
          <template slot-scope="scope">
            <el-tag :type="getCreditLevelType(scope.row.creditScore)" size="small">
              {{ getCreditLevel(scope.row.creditScore) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'" size="small">
              {{ scope.row.status === '0' ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleView(scope.row)"
            >详情</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 用户详情对话框 -->
    <el-dialog title="用户详情" :visible.sync="detailDialogVisible" width="600px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="用户ID">{{ currentUser.userId || '--' }}</el-descriptions-item>
        <el-descriptions-item label="用户名称">{{ currentUser.userName || '--' }}</el-descriptions-item>
        <el-descriptions-item label="手机号码">{{ currentUser.phonenumber || '--' }}</el-descriptions-item>
        <el-descriptions-item label="信用分">
          <el-tag :type="getCreditScoreType(currentUser.creditScore)" size="medium">
            {{ currentUser.creditScore || '--' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="信用等级">
          <el-tag :type="getCreditLevelType(currentUser.creditScore)" size="small">
            {{ getCreditLevel(currentUser.creditScore) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="currentUser.status === '0' ? 'success' : 'danger'" size="small">
            {{ currentUser.status === '0' ? '正常' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body @opened="onDialogOpened">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名称" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入用户名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input v-model="form.phonenumber" placeholder="请输入手机号码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-select v-model="form.sex" placeholder="请选择性别">
                <el-option label="男" value="0" />
                <el-option label="女" value="1" />
                <el-option label="未知" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idCard">
              <el-input v-model="form.idCard" placeholder="请输入身份证号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input-number v-model="form.age" :min="1" :max="120" :step="1" placeholder="请输入年龄" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="职业" prop="occupation">
              <el-input v-model="form.occupation" placeholder="请输入职业" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收入" prop="income">
              <el-input-number v-model="form.income" :min="0" :max="999999" :step="100" placeholder="请输入月收入" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="省份" prop="province">
              <el-input v-model="form.province" placeholder="请输入省份" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="城市" prop="city">
              <el-input v-model="form.city" placeholder="请输入城市" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="信用分" prop="creditScore">
              <el-input-number v-model="form.creditScore" :min="300" :max="850" :step="1" placeholder="请输入信用分" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态">
                <el-option label="正常" value="0" />
                <el-option label="禁用" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!form.userId">
          <el-col :span="12">
            <el-form-item label="登录密码" prop="password">
              <el-input v-model="form.password" type="password" placeholder="请输入登录密码" show-password />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input v-model="form.confirmPassword" type="password" placeholder="请确认登录密码" show-password />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注信息" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUserList, getUserInfo, updateUser, deleteUsers, exportUsers, addUser } from '@/api/credit/admin'

export default {
  name: 'CreditUserManagement',
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      selectedUsers: [],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: null,
        phonenumber: null
      },
      // 用户详情对话框
      detailDialogVisible: false,
      currentUser: {
        userId: null,
        userName: null,
        phonenumber: null,
        creditScore: null,
        status: null
      },
      // 新增/编辑用户对话框
      open: false,
      title: '',
      form: {
        userId: null,
        userName: null,
        phonenumber: null,
        email: null,
        sex: '0',
        idCard: null,
        age: 25,
        occupation: null,
        income: 5000,
        province: null,
        city: null,
        creditScore: 600,
        lifeServiceScore: 200,
        businessScore: 200,
        socialScore: 200,
        status: '0',
        password: null,
        confirmPassword: null,
        remark: null
      },
      rules: {
        userName: [
          { required: true, message: '用户名称不能为空', trigger: 'blur' },
          { min: 2, max: 20, message: '用户名称长度在2到20个字符', trigger: 'blur' }
        ],
        phonenumber: [
          { required: true, message: '手机号码不能为空', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
        ],
        email: [
          { required: false, message: '邮箱不能为空', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        idCard: [
          { required: true, message: '身份证号不能为空', trigger: 'blur' },
          { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '请输入正确的身份证号', trigger: 'blur' }
        ],
        age: [
          { required: true, message: '年龄不能为空', trigger: 'blur' },
          { type: 'number', min: 1, max: 120, message: '年龄范围为1-120岁', trigger: 'blur' }
        ],
        occupation: [
          { required: false, message: '职业不能为空', trigger: 'blur' }
        ],
        income: [
          { required: true, message: '收入不能为空', trigger: 'blur' },
          { type: 'number', min: 0, message: '收入不能为负数', trigger: 'blur' }
        ],
        province: [
          { required: false, message: '省份不能为空', trigger: 'blur' }
        ],
        city: [
          { required: false, message: '城市不能为空', trigger: 'blur' }
        ],
        creditScore: [
          { required: true, message: '信用分不能为空', trigger: 'blur' },
          { type: 'number', min: 300, max: 850, message: '信用分范围为300-850', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '登录密码不能为空', trigger: 'blur' },
          { min: 6, max: 20, message: '登录密码长度在6到20个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '确认密码不能为空', trigger: 'blur' },
          { validator: (rule, value, callback) => {
            if (value !== this.form.password) {
              callback(new Error('两次输入密码不一致'))
            } else {
              callback()
            }
          }, trigger: 'blur' }
        ]
      },
      submitLoading: false
    }
  },
  
  created() {
    this.getList()
  },
  
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true
      getUserList(this.queryParams).then(response => {
        this.userList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(error => {
        console.error('获取用户列表失败:', error)
        this.$modal.msgError('获取用户列表失败：' + (error.message || '未知错误'))
        this.userList = []
        this.total = 0
        this.loading = false
      })
    },
    
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    
    /** 重置按钮操作 */
    resetQuery() {
      if (this.$refs['queryForm']) {
        this.resetForm('queryForm')
      }
      this.handleQuery()
    },
    
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.selectedUsers = selection
      this.multiple = !selection.length
    },
    
    /** 查看用户详情 */
    handleView(row) {
      this.currentUser = {
        userId: row.userId || null,
        userName: row.userName || null,
        phonenumber: row.phonenumber || null,
        creditScore: row.creditScore || null,
        status: row.status || null
      }
      this.detailDialogVisible = true
    },

    /** 新增用户 */
    handleAdd() {
      this.title = '添加用户'
      this.form = {
        userId: null,
        userName: null,
        phonenumber: null,
        email: null,
        sex: '0',
        idCard: null,
        age: 25,
        occupation: null,
        income: 5000,
        province: null,
        city: null,
        creditScore: 600,
        lifeServiceScore: 200,
        businessScore: 200,
        socialScore: 200,
        status: '0',
        password: null,
        confirmPassword: null,
        remark: null
      }
      this.open = true
    },

    /** 编辑用户 */
    handleUpdate(row) {
      this.title = '修改用户'
      const userId = row.userId || row.user_id
      getUserInfo(userId).then(response => {
        this.form = response.data
        this.open = true
      }).catch(error => {
        this.$modal.msgError('获取用户信息失败：' + (error.message || '未知错误'))
      })
    },

    /** 弹窗完全打开后重置表单，防止resetFields报错 */
    onDialogOpened() {
      this.resetForm('form')
    },

    /** 删除用户 */
    handleDelete(row) {
      const userIds = row.userId || row.user_id
      this.$modal.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？').then(() => {
        return deleteUsers(userIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },

    /** 取消按钮 */
    cancel() {
      this.open = false
    },

    /** 表单提交 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.submitLoading = true
          if (this.form.userId != null) {
            updateUser(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            }).catch(error => {
              this.$modal.msgError('修改失败：' + (error.message || '未知错误'))
            }).finally(() => {
              this.submitLoading = false
            })
          } else {
            addUser(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            }).catch(error => {
              this.$modal.msgError('新增失败：' + (error.message || '未知错误'))
            }).finally(() => {
              this.submitLoading = false
            })
          }
        }
      })
    },

    /** 重置表单 */
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields()
      }
    },

    /** 刷新数据 */
    refreshData() {
      this.getList()
      this.$message.success('数据已刷新')
    },

    /** 导出 */
    handleExport() {
      this.$modal.confirm('是否确认导出所有用户数据项？').then(() => {
        this.loading = true
        return exportUsers(this.queryParams)
      }).then(response => {
        this.$download.name(response, '用户数据.xlsx')
      }).catch(() => {}).finally(() => {
        this.loading = false
      })
    },
    
    /** 获取信用分类型 */
    getCreditScoreType(score) {
      if (!score) return 'info'
      if (score >= 800) return 'success'
      if (score >= 750) return 'primary'
      if (score >= 700) return 'warning'
      if (score >= 650) return 'danger'
      return 'info'
    },
    
    /** 获取信用等级 */
    getCreditLevel(score) {
      if (!score) return '未知'
      if (score >= 800) return '优秀'
      if (score >= 750) return '良好'
      if (score >= 700) return '中等'
      if (score >= 650) return '一般'
      return '较差'
    },
    
    /** 获取信用等级类型 */
    getCreditLevelType(score) {
      if (!score) return 'info'
      if (score >= 800) return 'success'
      if (score >= 750) return 'primary'
      if (score >= 700) return 'warning'
      if (score >= 650) return 'danger'
      return 'info'
    }
  }
}
</script>

<style lang="scss" scoped>
.user-management {
  padding: 20px;
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .table-card {
    .mb8 {
      margin-bottom: 8px;
    }
  }
  
  .text-success {
    color: #67C23A;
  }
  
  .text-danger {
    color: #F56C6C;
  }
}
</style> 